import {Upload} from "antd";
import {host} from "@/requestErrorConfig";
import {beforeUpload} from "@/utils/upload";
import {LoadingOutlined, PlusOutlined} from "@ant-design/icons";
import {useState} from "react";

const AliyunOSSUploads = props => {

  let {onChange} = props;
  let {images, setImages, size, len, accept} = props.data;
  const [uploading, setUploading] = useState(false);

  /* 上传监听 */
  const handleChange = (info) => {
    setImages(info.fileList);
    if (info.file.status === 'uploading') {
      setUploading(true);
      return;
    }
    if (info.file.status === 'done') {
      setUploading(false);
      let response = {...info.file.response};
      if (response.code !== 0) {
        info.file.status = 'error';
        info.file.response = '上传失败';
      } else {
        info.file.uid = response.data.url;
        info.file.name = response.data.name;
        info.file.status = 'done';
        info.file.url = response.data.url;
      }
    }
    onChange(info);
  };

  return (
    <Upload
      name="file" action={`${host}/aliyun-oss/upload`}
      headers={{tenantToken: window.localStorage.getItem('token')}}
      beforeUpload={(file) => beforeUpload(file, size)}
      onChange={(info) => handleChange(info)}
      fileList={images}
      accept={accept} listType="picture-card">
      {(images.length < len) && (
        <div>
          {uploading ? <LoadingOutlined/> : <PlusOutlined/>}
          <div
            style={{
              marginTop: 8,
            }}
          >
            上传图片
          </div>
        </div>
      )}
    </Upload>
  );
};

export default AliyunOSSUploads;